﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;

namespace d39
{
    public partial class BBCodeBox : GridControl
    {
        protected override void UpdateFromGrid(bool playersOrMovesChanged, bool wallTerrainChanged)
        {
            UpdatePanel.Update();
            BBCode.Text = GetBBCode(CurrentGrid);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            ScriptManager.RegisterStartupScript(Page, typeof(BBCodeBox), "click", @"$('.bbcodebox').click(function() {this.select()});", true);
        }

        private static string getImageBBCode(Grid grid, UrlTweaks tweaks)
        {
            return "[img width=" + grid.GetImageWidth(tweaks) + " height=" + grid.GetImageHeight(tweaks) + "]" + grid.GetImageUrl(tweaks) + "[/img]";
        }
        private static string getLinkedImageBBCode(Grid grid, string page, UrlTweaks linkTweaks, UrlTweaks imageTweaks)
        {
            return "[url=" + grid.GetPageUrl("GridMove", linkTweaks) + "]" + getImageBBCode(grid, imageTweaks) + "[/url]";
        }

        private static string GetBBCode(Grid grid)
        {
            var result = "";
            if (grid.KnownMoves.Any())
            {
                result += string.Join("\r\n", from move in grid.KnownMoves select "[b][color=" + ColorTranslator.ToHtml(move.Player.Color) + "]" + move.GetMoveString(grid.DnDVersion) + "[/color][/b]");
                result += "\r\n\r\n";
            }
            var gridImageTweaks = new UrlTweaks() { IncludeDescriptions = false, RevealUnknown = false };
            var linkTweaks = new UrlTweaks() { IncludeMoves = false, RevealUnknown = false };
            var legendTweaks = new UrlTweaks()
            {
                ForceSizeToZero = true,
                IncludeLegendInImage = true,
                IncludeWalls = false,
                IncludeTerrain = false,
                IncludeEffects = false,
                IncludeMoves = false,
                IncludeGridLineColor = false,
                RevealUnknown = false,
            };
            result += "[table][tr][td]" + getLinkedImageBBCode(grid, "GridMove", linkTweaks, gridImageTweaks);
            if (grid.KnownPlayers.Any()) result += "[/td]\r\n[td]" + getImageBBCode(grid, legendTweaks);
            return result + "[/td][/tr][/table]";
        }
    }
}